package com.miao.teacher.utils;

import android.media.MediaPlayer;
import android.os.Handler;

public class SubMediaPlayer {
	private MediaPlayer mediaPlayer = null;
	private Runnable runnable = null;
	private Handler handler = null;
	private String url = "";

	public void setMediaFile(String u, Handler h) {
		handler = h;
		url = u;
	}

	public void play(final int start, final int length) {
		try {
			if (mediaPlayer != null) {
				mediaPlayer.stop();
				mediaPlayer.release();
			}
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare();

			mediaPlayer.seekTo(start);
			mediaPlayer.start();
			runnable = new Runnable() {
				@Override
				public void run() {
					try {
						if (mediaPlayer != null) {
							if (mediaPlayer.getCurrentPosition() >= start
									+ length) {
								mediaPlayer.stop();
								handler.obtainMessage(0).sendToTarget();
							} else {
								handler.postDelayed(runnable, 100);
							}
							if (!mediaPlayer.isPlaying()) {
								handler.obtainMessage(0).sendToTarget();
							}
						}
					} catch (Exception er) {
					}
				}
			};
			handler.postDelayed(runnable, 100);
		} catch (Exception er) {

		}
	}

	public void DoStop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
		}
	}
}
